<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { Form, message } from 'ant-design-vue';
import dayjs from 'dayjs'; // 引入 dayjs 用于时间格式化
import { getCfgExtDutyItemApi, putCfgExtDutyApi } from '@/common/apis/attendance'

const useForm = Form.useForm;

const labelCol = { span: 4 };
const wrapperCol = { span: 14 };
const dateFormat = 'HH:mm'
const dateFormat1 = 'MM/DD'
const size = ref(10)

// 使用 Record 来存储每个 id 的 checked 状态
const checkedSwitch = ref<Record<number, boolean>>({});
// 调休假 - 多选框
const checkbox = ref<Record<number, boolean>>({});
// 打卡验证
const isClock = ref(false);
// 是否开启补偿
const isCompensationint = ref(false)
// 储存加班规则数据
const extDutyData = ref()

const modelRef = reactive({
    unit: '',
    latestEffectDate: null as dayjs.Dayjs | null,
    isCompensationint: 1,
});

// props
const props = defineProps({
    closeModel: {
        type: Function,
        required: true
    },
    departmentId: {
        type: Number,
        required: true
    }
})

// 规则校验
const rulesRef = reactive({
    unit: [
        {
            required: true,
            message: '数据不能为空'
        },
        {
            type: 'number',
            min: 0.5,
            max: 10,
            message: '最小单位不能低于0.5天,最高不能高于10天',
            trigger: 'blur',
            transform: (value: string) => parseFloat(value) // 将字符串转换为数字
        }
    ],
    latestEffectDate: [
        {
            required: true,
            message: '日期不能为空'
        },
    ]
})

const { validate, validateInfos } = useForm(modelRef, rulesRef);

// 将时间字符串转换为 dayjs 对象
const parseTimeString = (timeString: string) => {
    return dayjs(`03-20 ${timeString}`); // 使用固定日期，仅用于时间格式化
};

// 初始化 checked 状态
const initCheckedStates = () => {
    extDutyData.value.extraDutyRuleList.forEach(item => {
        checkedSwitch.value[item.id] = item.isEnable === 1; // 1 -> true, 0 -> false
        checkbox.value[item.id] = item.isTimeOff === 1; // 1 -> true, 0 -> false
    });
};

// 初始化 workingDays 状态
const initWorkingDays = () => {
    extDutyData.value.extraDutyRuleList.forEach(item => {
        item.workingDays = [
            parseTimeString(item.ruleStartTime),
            parseTimeString(item.ruleEndTime),
        ];
    });
};

// 初始化配置状态
const initConfigStates = () => {
    isClock.value = extDutyData.value.extraDutyConfig.isClock === 1;
    isCompensationint.value = extDutyData.value.extraDutyConfig.isCompensationint === 1;
};

// 初始化 modelRef 数据
const initModelRef = () => {
    modelRef.unit = extDutyData.value.dayOffConfigs.unit;
    modelRef.latestEffectDate = dayjs(extDutyData.value.dayOffConfigs.latestEffectDate)
};

// 获取考勤加班规则
const getCfgExtDutyItemData = async () => {
    const res = await getCfgExtDutyItemApi({ departmentId: props.departmentId });
    extDutyData.value = res.data.data;
    initCheckedStates();
    initWorkingDays();
    initConfigStates();
    initModelRef();
};

// 点击确认
const onSubmit = () => {
    validate().then(() => {
        // 构造部门配置数据
        const submitData = {
            departmentId: props.departmentId,
            isClock: isClock.value ? 1 : 0,
            isCompensationint: isCompensationint.value ? 1 : 0,
            latestEffectDate: modelRef.latestEffectDate?.format('YYYY-MM-DD'), // 转换为字符串
            unit: modelRef.unit,
            rules: extDutyData.value.extraDutyRuleList.map(item => ({
                departmentId: props.departmentId,
                rule: item.rule,
                ruleStartTime: item.workingDays[0]?.format('HH:mm:ss'), // 转换为字符串
                ruleEndTime: item.workingDays[1]?.format('HH:mm:ss'), // 转换为字符串
                isTimeOff: checkbox.value[item.id] ? 1 : 0, // true -> 1, false -> 0
                isEnable: checkedSwitch.value[item.id] ? 1 : 0, // true -> 1, false -> 0
            })),
        };

        // 调用接口
        putCfgExtDutyApi(submitData).then(res => {
            console.log(res)
            message.success(res.data.message)
            // 关闭弹框
            props.closeModel();
        }).catch(err => {
            console.log(err, 'asfdafasf')
            message.warning(err.response.data.message)
        });
    });
};

// 侦听 departmentID 变化
watch(
    () => props.departmentId,
    (newVal) => {
        if (newVal) {
            console.log('departmentId发生变化', newVal);
            getCfgExtDutyItemData();
        }
    },
    { immediate: true }  // 立刻执行一次
);

onMounted(() => {
    getCfgExtDutyItemData();
});
</script>

<template>
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol" class="overtime">
        <!-- 加班规则 -->
        <a-form-item label="加班规则：">
            <div v-for="item in extDutyData?.extraDutyRuleList" :key="item.id" class="overtime-work">
                <div>
                    <a-space :size="size" v-model:value="size">
                        <a-switch v-model:checked="checkedSwitch[item.id]" />
                        <span>{{ item.rule }}</span>
                    </a-space>
                </div>
                <div class="overtime-overtime1">
                    <a-space :size="size">
                        <a-checkbox v-model:checked="checkbox[item.id]">多选框</a-checkbox>
                        <!-- 为每个 item 绑定独立的 workingDays -->
                        <a-time-range-picker style="width: 190px; margin-top: 5px;" v-model:value="item.workingDays"
                            :format="dateFormat" />
                    </a-space>
                </div>
            </div>
        </a-form-item>
        <!-- 打卡验证 -->
        <a-form-item label="打卡验证：">
            <a-space v-model:value="size">
                <a-switch v-model:checked="isClock" />
                <span>加班需要打卡记录</span>
            </a-space>
        </a-form-item>
        <!-- 开启补偿 -->
        <a-form-item label="开启补偿：">
            <a-switch v-model:checked="isCompensationint" />
        </a-form-item>
        <!-- 调休假设置 -->
        <a-form-item label="调休假设置：" v-bind="validateInfos.latestEffectDate" class="overtime-vacation">
            最晚有效期：<a-date-picker v-model:value="modelRef.latestEffectDate" :format="dateFormat1" />
        </a-form-item>
        <a-form-item label="调休假设置： " v-bind="validateInfos.unit">
            <div class="overtime-firm">
                请假最小单位：<a-input style="width: 60px;" :min="0.5" :max="10" v-model:value="modelRef.unit" /> 天
            </div>
        </a-form-item>
        <!-- 确定按钮 -->
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click.prevent="onSubmit">保存更新</a-button>
        </a-form-item>
    </a-form>
</template>

<style lang="scss" scoped>
.overtime {
    &-work {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    &-firm {
        display: flex;
        align-items: center;
    }
}
</style>